package com.fubowen.lepton.components

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

class StackLayoutManager(
    private val recyclerView: RecyclerView
) : RecyclerView.LayoutManager() {

    init {
        recyclerView.onFlingListener = FlingListener()
    }

    override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
        return RecyclerView.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
    }

    override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) {
        detachAndScrapAttachedViews(recycler)
        val left = paddingLeft
        val top = paddingTop
        val right = width - paddingRight
        val bottom = height - paddingBottom
        val preloadCount = if (itemCount > 2) 2 else itemCount
        for (i in preloadCount - 1 downTo 0) {
            val child = recycler.getViewForPosition(i)
            addView(child)
            measureChildWithMargins(child, 0, 0)
            layoutDecorated(child, left, top, right, bottom)
        }
    }

    override fun canScrollHorizontally(): Boolean {
        return true
    }

    override fun scrollHorizontallyBy(
        dx: Int,
        recycler: RecyclerView.Recycler,
        state: RecyclerView.State
    ): Int {
        var scrolled = 0
        val leftEdge = paddingLeft
        val rightEdge = width - paddingRight
        var center = paddingLeft + width / 2
        var move = dx
        val view = getChildAt(childCount - 1)
        isSmoothScrolling
        view?.let {
            it.offsetLeftAndRight(-dx)
            if (isSmoothScrolling) {
                val right = getDecoratedRight(it)
                if (right < center) {
//                it.offsetLeftAndRight(-right)
                    it.scrollBy(-right, 0)
                    move += -right
                }
            }
        }

        return move
    }

    private inner class FlingListener : RecyclerView.OnFlingListener() {
        override fun onFling(velocityX: Int, velocityY: Int): Boolean {
            if (velocityX == 0 && velocityY == 0) {
            }
            return false
        }
    }
}